package com.kapo.egroup.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kapo.egroup.common.ResponseEnum;
import com.kapo.egroup.common.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Title LoginFailureHandler
 * @Description TODO
 * @Author 黄家宝
 * @Date 2022-10-13 01:07
 **/
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        ServletOutputStream outputStream = response.getOutputStream();
        ResponseEnum responseEnum = null;
        //判断异常类型
        if (exception instanceof AccountExpiredException) {
            responseEnum = ResponseEnum.LOGIN_EXPIRED;
        } else if (exception instanceof BadCredentialsException) {
            responseEnum = ResponseEnum.CREDENTIALS_WRONG;
        } else if (exception instanceof CredentialsExpiredException) {
            responseEnum = ResponseEnum.LOGIN_FAILED;
        } else if (exception instanceof DisabledException) {
            responseEnum = ResponseEnum.DISABLED_CREDENTIALS;
        } else if (exception instanceof LockedException) {
            responseEnum = ResponseEnum.LOCKED_CREDENTIALS;
        } else if (exception instanceof InternalAuthenticationServiceException) {
            responseEnum = ResponseEnum.LOGIN_FAILED;
        }else {
            responseEnum = ResponseEnum.LOGIN_FAILED;
        }
        Result result = Result.fail().result(responseEnum);
        String res = JSON.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect);
        outputStream.write(res.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
